﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- 常用搜索条件 -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="BillNo_FormItem" prop="BillNo">
							<template #label>
								<WtmLabelTooltip label="单号" tooltip="用人需求池单号" />
							</template>
							<el-input v-model="searchData.BillNo" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<WtmDeptSelector v-model="searchData.GroupId" label="部门" :rules="[]" :auth="false" />
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="HrStatus_FormItem" prop="HrStatus">
							<template #label>
								<WtmLabelTooltip label="状态" tooltip="单据状态" />
							</template>
							<el-select v-model="searchData.HrStatus" clearable>
								<el-option key="申请中" value="申请中" label="申请中"></el-option>
								<el-option key="已审核" value="已审核" label="已审核"></el-option>
								<el-option key="已拒绝" value="已拒绝" label="已拒绝"></el-option>
								<el-option key="已面试" value="已面试" label="已面试"></el-option>
								<el-option key="面试通过" value="面试通过" label="面试通过"></el-option>
								<el-option key="面试未通过" value="面试未通过" label="面试未通过"></el-option>
								<el-option key="体检中" value="体检中" label="体检中"></el-option>
								<el-option key="体检通过" value="体检通过" label="体检通过"></el-option>
								<el-option key="体检未通过" value="体检未通过" label="体检未通过"></el-option>
								<el-option key="背调中" value="背调中" label="背调中"></el-option>
								<el-option key="背调通过" value="背调通过" label="背调通过"></el-option>
								<el-option key="背调未通过" value="背调未通过" label="背调未通过"></el-option>
								<el-option key="Offer已发" value="Offer已发" label="Offer已发"></el-option>
								<el-option key="Offer已接受" value="Offer已接受" label="Offer已接受"></el-option>
								<el-option key="Offer已拒绝" value="Offer已拒绝" label="Offer已拒绝"></el-option>
								<el-option key="已录用" value="已录用" label="已录用"></el-option>
								<el-option key="已入职" value="已入职" label="已入职"></el-option>
								<el-option key="已报到" value="已报到" label="已报到"></el-option>
								<el-option key="入职资料待完善" value="入职资料待完善" label="入职资料待完善"></el-option>
								<el-option key="试用中" value="试用中" label="试用中"></el-option>
								<el-option key="已转正" value="已转正" label="已转正"></el-option>
								<el-option key="已放弃" value="已放弃" label="已放弃"></el-option>
								<el-option key="已淘汰" value="已淘汰" label="已淘汰"></el-option>
								<el-option key="离职办理中" value="离职办理中" label="离职办理中"></el-option>
								<el-option key="已离职" value="已离职" label="已离职"></el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<!-- 暂时没有其他高级搜索条件，保留扩展结构 -->
					<template v-if="showAdvanced">
						<!-- 预留高级搜索条件扩展位置 -->
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysHrStaffPool/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrStaffPool/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysHrStaffPool/GenerateRecruitPublishRequest'"
				icon="fa fa-external-link"
				type="success"
				button-text="生成发布申请"
				:disabled="!hasSelectedRows"
				confirm="确定要为选中的招聘需求生成发布申请单吗？"
				@click="onBatchGenerateRecruitRequest()"
			/>
			<WtmButton
				v-auth="'/api/SysHrStaffPool/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrStaffPool/SysHrStaffPoolExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" width="120" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysHrStaffPool/Edit'"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrStaffPool/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrStaffPool/BatchDelete'"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="用人需求池;true;HengTong.Areas.Hr.Controllers;SysHrStaffPool">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysHrStaffPoolApi as api } from '/@/views/hr/syshrstaffpool/api';
import { ISysHrStaffPoolView, ISysHrStaffPoolQuery } from '/@/views/hr/syshrstaffpool/api/interface';
import other from '/@/utils/other';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

// 打开招聘需求申请弹窗
// const ModifyRecruitNumberDialog = defineAsyncComponent(() => import('/@/views/hr/syshrrecruitrequestbill/edit.vue'));
const ModifyRecruitNumberDialog = defineAsyncComponent(() => import('/@/views/hr/syshrrecruitpublishrequestbill/edit.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysHrStaffPoolQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: false,
		filters: () => ({}),
		entityId: null,
	}
);

const searchData = ref<ISysHrStaffPoolQuery>({});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）
	data: [],
	// 表头内容（必传，注意格式）
	header: [
		{ title: '用人需求池单号', key: 'BillNo', type: 'text', isCheck: true },
		{ title: '状态', key: 'HrStatus', type: 'text', isCheck: true },
		{ title: '公司', key: 'OrgName', type: 'text', isCheck: true, width: '150' },
		{ title: '部门', key: 'GroupName', type: 'text', isCheck: true },
		{ title: '岗位', key: 'JobPositionName', type: 'text', isCheck: true },
		{ title: '需求人数', key: 'HireNumber', type: 'text', isCheck: true },
		{ title: '到岗时间', key: 'ExpectedDate', type: 'text', isCheck: true },
		{ title: '单据状态', key: 'BillStatus', type: 'text', isCheck: true },
		{ title: '学历要求', key: 'EducationRequirement', type: 'text', isCheck: true },
		{ title: '专业要求', key: 'MajorRequirement', type: 'text', isCheck: true },
		{ title: '年龄要求', key: 'AgeRequirement', type: 'text', isCheck: true },
		{ title: '性别要求', key: 'GenderRequirement', type: 'text', isCheck: true },
		{ title: '岗位要求', key: 'JobRequirement', type: 'text', isCheck: true },
		{ title: '申请原因', key: 'ApplyReason', type: 'text', isCheck: true },
		{ title: '其他要求', key: 'OtherRequirement', type: 'text', isCheck: true },
		{ title: '备注', key: 'Remark', type: 'text', isCheck: true },
		{ title: '用人申请单号', key: 'BillCode', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, null, getTableData);
};

const OnEditRowClick = (row: ISysHrStaffPoolView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysHrStaffPoolView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysHrStaffPoolView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysHrStaffPoolView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		loading.value = true;
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		} finally {
			loading.value = false;
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};

//批量生成招聘需求申请
const onBatchGenerateRecruitRequest = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();

	if (selectedRows && selectedRows.length > 0) {
		// 提取有效的ID
		const validIds = selectedRows
			.map((x: ISysHrStaffPoolView) => x.ID)
			.filter((id: string | number | null | undefined): id is string | number => id !== null && id !== undefined);

		loading.value = true;
		try {
			const response = await api().batchGenerateRecruitRequest(validIds);

			// 根据返回的状态码判断操作是否成功
			if (response.Code == 200) {
				// 先清除选择状态
				tableRef.value?.clearSelection();
				// 再重新获取数据
				getTableData();
				ElMessage.success('批量生成招聘发布申请成功');
				other.openDialog('招聘发布', ModifyRecruitNumberDialog, { ID: response.Data }, getTableData);
			} else {
				// 显示后端返回的错误信息
				ElMessage.error(response.Message || '操作失败');
			}
		} catch (error: any) {
			// 如果是网络错误或其他异常，显示通用错误信息
			if (error.response?.Data?.Message) {
				ElMessage.error(error.response.Data.Message);
			} else {
				ElMessage.error('操作失败，请稍后重试');
			}
		} finally {
			loading.value = false;
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	const promises: Promise<any>[] = [getTableData()];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
